import random
import util
import file


def print_user(account, a_dict):
    print(f"当前账户：{account}")
    print(f"密码：{a_dict[pw_key]}\t余额：{a_dict[bl_key]}\t开户行：{a_dict[bk_key]}\t")
    ar_dict = a_dict[ar_key]
    print(
        f"用户居住地址：(国家：{ar_dict[ct_key]}，省市：{ar_dict[pv_key]}，街道：{ar_dict[street_key]}，门牌号：{ar_dict[dn_key]})")


def search():
    global user_lib
    account = input("请输入转出账户")
    account_dict = user_lib.get(account)
    if account_dict is None:
        print("该用户不存在")
    input_pw = input("请输入密码")
    print(type(input_pw))
    store_pw = account_dict.get(pw_key)
    if store_pw != input_pw:
        print("密码不对")
    print_user(account, account_dict)


def transfer():
    # print("转账")
    from_account = get_account(input("转出账户："))
    to_account = get_account(input("转入账户："))
    if not (from_account and to_account):
        return 1
    if not verify_password(from_account, input("密码")):
        return 2
    amount = get_integer_input("请输入转账金额")
    if not has_sufficient_funds(from_account, amount):
        return 3
    process_transaction(from_account, amount, 'withdraw')
    process_transaction(to_account, amount, 'deposit')
    return 0


# 将所有金额操作改为整数处理
def process_transaction(account, amount, operation):
    if operation == 'deposit':
        account[bl_key] += amount
    elif operation == 'withdraw':
        account[bl_key] -= amount
    save_changes()


def take_out():
    global user_lib
    account_num = input("请输入账号：")
    account = user_lib.get(account_num)
    if not account:
        return 1
    input_pw = input("请输入密码：")
    if not verify_password(account, input_pw):
        return 2
    amount = get_integer_input("请输入要取出的金额")
    if not has_sufficient_funds(account, amount):
        return 3

    process_transaction(account, amount, 'withdraw')
    return 0


# 传入值：用户的账号、存取的金额
def process_saving(account, transaction_amount):
    global user_lib
    account_dict = user_lib.get(account)
    account_dict['balance'] += transaction_amount
    user_lib[account] = account_dict
    file.write_to_file(user_lib, 'w')
    return True


# 返回值：布尔类型值
def saving():
    account = input("请输入账号：")
    if not util.is_account_exist(account):
        return False
    try:
        amount = float(input("请输入存取的金额："))
        return process_saving(account, amount)
    except ValueError:
        print("请输入合法的金额")


def create_info():
    """
    用户信息内容：姓名、密码、地址、存款余额、开户行
    地址内容：
    属性映射：
      用户: 姓名:name、密码:password、地址:address、存款余额:balance、开户行:bank
      地址: 国家:country、省份:province、街道:street、门牌号:door_number
    属性约束：
      用户信息字典 {name:str,password:int(6),address:dict,balance:int,bank:str}
      地址字典 {country:str,province:strs,street:str,door_number:str}
          不用用户输入的：账户、存款余额（开户时默认为0）、开户行
          需要用户输入的：姓名、密码、地址、存款余额、国家、省份、街道、门牌号
    """
    address_att_dict = {ct_key: '请输入国家', pv_key: '请输入省份', street_key: '请输入街道',
                        'door_number': '请输入门牌号'}
    new_info = {'name': input("请输入姓名："), pw_key: util.valid_password()}
    # 地址创建
    new_address = {}
    for attribute, tips in address_att_dict.items():
        content = input(tips + "：")
        new_address[attribute] = content
    new_info[ar_key] = new_address
    new_info[bl_key] = 0.0
    new_info[bk_key] = bank_name
    return new_info


# 开户
def open_account():
    new_info = create_info()
    account_num = str(random.randint(10 ** 7, 10 ** 8 - 1))
    if util.is_account_exist(account_num):
        return 2
    if util.get_account_count() >= 100:
        return 3
    global user_lib
    user_lib[account_num] = new_info
    file.write_to_file(user_lib, 'w')
    return 1


def get_integer_input(prompt):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("请输入整数金额")


# 账号操作工具函数
def get_account(account_num):
    return user_lib.get(account_num)


# 密码验证函数
def verify_password(account, input_pw):
    return account and account[pw_key] == int(input_pw)


# 余额验证函数
def has_sufficient_funds(account, amount):
    return account and account[bl_key] >= amount


# 持久化存储
def save_changes():
    file.write_to_file(user_lib, 'w')


def menu():
    while True:
        print(divider)
        print(title)
        opt_input = util.option_input(opt_list, divider, 38)
        option = opt_dict.get(opt_input)
        res = option()
        if res is None:
            break
        op_res_dict = result_dict[opt_input]
        op_res = op_res_dict[res]
        print(op_res)


name_key = 'name'
pw_key = 'password'
bk_key = 'bank'
bl_key = 'balance'
ar_key = 'address'
ct_key = 'country'
pv_key = 'province'
street_key = 'street'
dn_key = 'door_number'
user_lib = file.get_account_from_file()
divider = '*' * 40
title = "* 中国工商银行 账户管理系统 V1.0".ljust(32) + "*"
opt_list = ['开户', '存钱', '取钱', '转账', '查询', 'Bye！']
opt_dict = {
    "1": open_account,
    '2': saving,
    '3': take_out,
    '4': transfer,
    '5': search,
    '6': exit
}
result_dict = {
    "1": {1: "成功", 2: "账户已存在", 3: "用户库已满"},
    '2': {True: "存款成功", False: "没有该用户"},
    '3': {0: "正常", 1: "账号不存在", 2: "密码不对", 3: "钱不够"},
    '4': {0: "正常", 1: "账号不存在", 2: "密码不对", 3: "钱不够"},
}
bank_name = "中国工商银行昌平支行"
menu()
